<template>
  <div class="app-container">
    <el-form :model="searchForm" ref="searchFormRef" inline v-show="showSearch">
      <el-form-item label="授权码" prop="like.license_key" class="w-200px">
        <el-input v-model="searchForm.like.license_key" placeholder="请输入授权码" clearable @keyup.enter="search" />
      </el-form-item>
      <el-form-item label="状态" prop="where.status" class="w-180px">
        <el-select v-model="searchForm.where.status" placeholder="请选择状态" clearable>
          <el-option label="正常" :value="1" />
          <el-option label="已过期" :value="2" />
          <el-option label="已禁用" :value="3" />
          <el-option label="已冻结" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="search">搜索</el-button>
        <el-button icon="Refresh" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="mb-8px w-full">
      <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPerm="['license:license:add']">新增</el-button>
      <el-button type="success" plain icon="Download" @click="handleExport" v-hasPerm="['license:license:export']">导出</el-button>
      <right-toolbar v-model:showSearch="showSearch" @refresh="getList" v-model:columns="columns" />
    </div>

    <el-table v-loading="loading" :data="listData">
      <template v-for="item in columns">
        <el-table-column
          align="center"
          :key="item.key"
          :prop="item.key"
          :label="item.label"
          :show-overflow-tooltip="!!item.overflow"
          :width="item.width"
          v-if="item.show">
          <template v-slot="{ row }">
            <span v-if="item.key === 'status'">
              <el-tag v-if="row.status === 1" type="success">正常</el-tag>
              <el-tag v-else-if="row.status === 2" type="danger">已过期</el-tag>
              <el-tag v-else-if="row.status === 3" type="info">已禁用</el-tag>
              <el-tag v-else type="warning">已冻结</el-tag>
            </span>
            <span v-else-if="item.key === 'remaining_days'">
              <el-tag v-if="row.remaining_days > 30" type="success">{{ row.remaining_days }}天</el-tag>
              <el-tag v-else-if="row.remaining_days > 0" type="warning">{{ row.remaining_days }}天</el-tag>
              <el-tag v-else type="danger">已过期</el-tag>
            </span>
            <span v-else>{{ row[item.key] }}</span>
          </template>
        </el-table-column>
      </template>

      <el-table-column label="操作" align="center" width="280" fixed="right">
        <template v-slot="{ row }">
          <el-button link type="primary" icon="View" @click="handleView(row)" v-hasPerm="['license:license:query']">详情</el-button>
          <el-button link type="primary" icon="Edit" @click="handleEdit(row)" v-hasPerm="['license:license:edit']">编辑</el-button>
          <el-button link type="warning" icon="Refresh" @click="handleRenew(row)">续期</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(row)" v-hasPerm="['license:license:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="page" v-model:limit="limit" @pagination="getList" />

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="800px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户" prop="customer_id">
              <el-select v-model="form.customer_id" placeholder="请选择客户" filterable style="width: 100%">
                <el-option v-for="item in customerList" :key="item.id" :label="item.customer_name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品" prop="product_id">
              <el-select v-model="form.product_id" placeholder="请选择产品" filterable style="width: 100%">
                <el-option v-for="item in productList" :key="item.id" :label="item.product_name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="授权类型" prop="license_type">
              <el-select v-model="form.license_type" placeholder="请选择授权类型" style="width: 100%">
                <el-option label="试用版" :value="1" />
                <el-option label="正式版" :value="2" />
                <el-option label="永久版" :value="3" />
                <el-option label="开发版" :value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="授权级别" prop="license_level">
              <el-select v-model="form.license_level" placeholder="请选择授权级别" style="width: 100%">
                <el-option label="基础版" value="basic" />
                <el-option label="专业版" value="professional" />
                <el-option label="企业版" value="enterprise" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="start_date">
              <el-date-picker
                v-model="form.start_date"
                type="datetime"
                placeholder="选择开始时间"
                style="width: 100%"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="end_date">
              <el-date-picker
                v-model="form.end_date"
                type="datetime"
                placeholder="选择结束时间"
                style="width: 100%"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最大用户数" prop="max_users">
              <el-input-number v-model="form.max_users" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大站点数" prop="max_sites">
              <el-input-number v-model="form.max_sites" :min="0" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="域名限制">
          <el-select v-model="form.domain" multiple filterable allow-create placeholder="请输入域名，回车添加" style="width: 100%">
          </el-select>
          <el-text type="info" size="small">支持多个域名，留空表示不限制</el-text>
        </el-form-item>
        <el-form-item label="IP白名单">
          <el-select v-model="form.ip_whitelist" multiple filterable allow-create placeholder="请输入IP地址，回车添加" style="width: 100%">
          </el-select>
          <el-text type="info" size="small">支持多个IP地址，留空表示不限制</el-text>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="授权详情" v-model="detailVisible" width="800px" append-to-body>
      <el-descriptions :column="2" border v-if="detailData">
        <el-descriptions-item label="授权码">{{ detailData.license_key }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ detailData.customer_name }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ detailData.product_name }}</el-descriptions-item>
        <el-descriptions-item label="授权类型">{{ detailData.license_type_text }}</el-descriptions-item>
        <el-descriptions-item label="授权级别">
          <span v-if="detailData.license_level === 'basic'">基础版</span>
          <span v-else-if="detailData.license_level === 'professional'">专业版</span>
          <span v-else-if="detailData.license_level === 'enterprise'">企业版</span>
          <span v-else>{{ detailData.license_level }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ detailData.start_date }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ detailData.end_date }}</el-descriptions-item>
        <el-descriptions-item label="剩余天数">
          <el-tag v-if="detailData.remaining_days > 30" type="success">{{ detailData.remaining_days }}天</el-tag>
          <el-tag v-else-if="detailData.remaining_days > 0" type="warning">{{ detailData.remaining_days }}天</el-tag>
          <el-tag v-else type="danger">已过期</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag v-if="detailData.status === 1" type="success">正常</el-tag>
          <el-tag v-else-if="detailData.status === 2" type="danger">已过期</el-tag>
          <el-tag v-else-if="detailData.status === 3" type="info">已禁用</el-tag>
          <el-tag v-else type="warning">已冻结</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="最大用户数">{{ detailData.max_users || '不限制' }}</el-descriptions-item>
        <el-descriptions-item label="最大站点数">{{ detailData.max_sites || '不限制' }}</el-descriptions-item>
        <el-descriptions-item label="域名限制" :span="2">
          <el-tag v-if="!detailData.domain_list || detailData.domain_list.length === 0" type="info">不限制</el-tag>
          <el-tag v-else v-for="domain in detailData.domain_list" :key="domain" class="mr-2">{{ domain }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="IP白名单" :span="2">
          <el-tag v-if="!detailData.ip_white_list || detailData.ip_white_list.length === 0" type="info">不限制</el-tag>
          <el-tag v-else v-for="ip in detailData.ip_white_list" :key="ip" class="mr-2">{{ ip }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailData.remark || '无' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailData.created_at }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailData.updated_at }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailVisible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 续期对话框 -->
    <el-dialog title="授权续期" v-model="renewVisible" width="400px" append-to-body>
      <el-form :model="renewForm" label-width="100px">
        <el-form-item label="续期月数">
          <el-input-number v-model="renewForm.months" :min="1" :max="120" />
          <el-text type="info" size="small" class="ml-2">最多120个月</el-text>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="renewVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitRenew" :loading="renewLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="LicenseList">
import { listLicense, getLicense, addLicense, updateLicense, delLicense, renewLicense } from '@/api/license/license'
import { listCustomer } from '@/api/license/customer'
import { listProduct } from '@/api/license/product'

const { proxy } = getCurrentInstance()

const listData = ref([])
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const page = ref(1)
const limit = ref(10)

const searchForm = ref({
  like: {
    license_key: ''
  },
  where: {
    status: ''
  }
})

const columns = ref([
  { key: 'id', label: 'ID', width: 80, show: true },
  { key: 'license_key', label: '授权码', show: true, overflow: true },
  { key: 'customer_name', label: '客户名称', width: 150, show: true, overflow: true },
  { key: 'product_name', label: '产品名称', width: 150, show: true, overflow: true },
  { key: 'license_type_text', label: '授权类型', width: 100, show: true },
  { key: 'status', label: '状态', width: 100, show: true },
  { key: 'remaining_days', label: '剩余天数', width: 120, show: true },
  { key: 'start_date', label: '开始时间', width: 180, show: false },
  { key: 'end_date', label: '结束时间', width: 180, show: true }
])

const searchFormRef = ref()
const formRef = ref()
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitLoading = ref(false)
const detailVisible = ref(false)
const detailData = ref(null)
const customerList = ref([])
const productList = ref([])

// 续期相关
const renewVisible = ref(false)
const renewLoading = ref(false)
const renewForm = ref({
  id: null,
  months: 12
})

const form = ref({
  id: null,
  customer_id: null,
  product_id: null,
  license_type: 2,
  license_level: 'basic',
  start_date: '',
  end_date: '',
  max_users: 0,
  max_sites: 0,
  domain: [],
  ip_whitelist: [],
  remark: ''
})

const rules = {
  customer_id: [{ required: true, message: '请选择客户', trigger: 'change' }],
  product_id: [{ required: true, message: '请选择产品', trigger: 'change' }],
  license_type: [{ required: true, message: '请选择授权类型', trigger: 'change' }],
  start_date: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  end_date: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
}

/** 查询列表 */
function getList() {
  loading.value = true
  const params = {
    page: page.value,
    limit: limit.value,
    like: searchForm.value.like,
    where: searchForm.value.where
  }
  listLicense(params)
    .then(response => {
      listData.value = response.list || []
      total.value = response.page?.total || 0
      loading.value = false
    })
    .catch(() => {
      loading.value = false
    })
}

/** 加载客户列表 */
function loadCustomers() {
  listCustomer({ page: 1, limit: 1000 }).then(res => {
    customerList.value = res.list || []
  })
}

/** 加载产品列表 */
function loadProducts() {
  listProduct({ page: 1, limit: 1000 }).then(res => {
    productList.value = res.list || []
  })
}

/** 搜索按钮操作 */
function search() {
  page.value = 1
  getList()
}

/** 重置按钮操作 */
function reset() {
  searchFormRef.value?.resetFields()
  search()
}

/** 重置表单 */
function resetForm() {
  form.value = {
    id: null,
    customer_id: null,
    product_id: null,
    license_type: 2,
    license_level: 'basic',
    start_date: '',
    end_date: '',
    max_users: 0,
    max_sites: 0,
    domain: [],
    ip_whitelist: [],
    remark: ''
  }
  formRef.value?.resetFields()
}

/** 新增按钮操作 */
function handleAdd() {
  resetForm()
  dialogTitle.value = '新增授权'
  dialogVisible.value = true
  loadCustomers()
  loadProducts()
}

/** 查看详情 */
function handleView(row) {
  getLicense({ id: row.id }).then(res => {
    detailData.value = res.info
    detailVisible.value = true
  })
}

/** 修改按钮操作 */
function handleEdit(row) {
  resetForm()
  getLicense({ id: row.id }).then(res => {
    const info = res.info
    form.value = {
      id: info.id,
      customer_id: info.customer_id,
      product_id: info.product_id,
      license_type: info.license_type,
      license_level: info.license_level,
      start_date: info.start_date,
      end_date: info.end_date,
      max_users: info.max_users,
      max_sites: info.max_sites,
      domain: info.domain_list || [],
      ip_whitelist: info.ip_white_list || [],
      remark: info.remark
    }
    dialogTitle.value = '编辑授权'
    dialogVisible.value = true
    loadCustomers()
    loadProducts()
  })
}

/** 提交表单 */
function submitForm() {
  formRef.value.validate(valid => {
    if (!valid) return

    submitLoading.value = true
    const submitData = { ...form.value }
    
    const submitFn = form.value.id ? updateLicense : addLicense
    submitFn(submitData)
      .then(() => {
        proxy.$modal.msgSuccess(form.value.id ? '修改成功' : '新增成功')
        dialogVisible.value = false
        getList()
      })
      .finally(() => {
        submitLoading.value = false
      })
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除该授权？')
    .then(() => {
      return delLicense({ id: row.id })
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 续期按钮操作 */
function handleRenew(row) {
  renewForm.value = {
    id: row.id,
    months: 12
  }
  renewVisible.value = true
}

/** 提交续期 */
function submitRenew() {
  renewLoading.value = true
  renewLicense(renewForm.value)
    .then(() => {
      proxy.$modal.msgSuccess('续期成功')
      renewVisible.value = false
      getList()
    })
    .finally(() => {
      renewLoading.value = false
    })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.$modal.msgWarning('导出功能开发中...')
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.mr-2 {
  margin-right: 8px;
  margin-bottom: 4px;
}
</style>
